<script setup>
import router from "@/router/index.js";
import {computed, onMounted, ref, onBeforeUnmount} from 'vue';
import {useTeamFormStore, useTeamTagStore} from "@/stores/index.js";
import {showToast} from "vant";
import {addTeam} from "@/api/team.js";

const onClickLeft = () => {
  router.back();
}

const timeDialog = ref(false);
const currentDate = ref([]);
const currentTime = ref([]);

const maxDate = new Date(2035, 8, 17);
const minDate = new Date(2015, 8, 17);
const beginOrEnd = ref(0);

/**
 * 确认选择时间
 */
const onConfirm = () => {
  if (beginOrEnd.value === 0) {
    teamForm.value.beginTime = currentDate.value.join('-') + ' ' + currentTime.value.join(':')
  } else if (beginOrEnd.value === 1) {
    teamForm.value.endTime = currentDate.value.join('-') + ' ' + currentTime.value.join(':')
  }
  timeDialog.value = false
};

/**
 * 取消选择时间
 */
const onCancel = () => {
  timeDialog.value = false;
}

/**
 * 队伍表单处理
 */
const teamForm = ref({
  teamName: '',
  image: '',
  teamDesc: '',
  maxMember: 0,
  type: 0,
  teamPassword: '',
  isJoin: 0,
  isFound: 0,
  geoX: 0,
  geoY: 0,
  isLimit: 0,
  beginTime: '',
  endTime: '',
  tags: []
});

/**
 * 选择时间
 */
const chooseTime = (flag) => {
  timeDialog.value = true;
  beginOrEnd.value = flag;
}

/**
 * 计算字数
 * @type {ComputedRef<number>}
 */
const charCount = computed(() => teamForm.value.teamDesc.length);

/**
 * Set current date and time
 */
const setDate = () => {
  const now = new Date();
  currentDate.value = [now.getFullYear().toString(), (now.getMonth() + 1).toString().padStart(2, '0'), now.getDate().toString().padStart(2, '0')];
  currentTime.value = [now.getHours().toString().padStart(2, '0'), now.getMinutes().toString().padStart(2, '0')];
}

/**
 * 创建队伍
 */
const onClickRight = () => {
  if (!validateTeamForm()) {
    return
  }

  addTeam(teamForm.value).then(res => {
    if (res.data.code === 1) {
      const { teamName, teamNumber } = res.data.data
      const formStore = useTeamFormStore()
      // eslint-disable-next-line no-undef
      showDialog({
        title: '创建成功',
        message: `队伍名称: ${teamName}\n队伍编号: ${teamNumber}`,
      }).then(() => {
        formStore.resetTeamForm()
        router.push('/team')
      });
    }else {
      showToast(res.data.msg)
    }
  }).catch(err => {
    console.log(err)
  })
}

const validateTeamForm = () => {
  const { teamName, teamDesc, maxMember, teamPassword } = teamForm.value;

  // 校验队伍名：二-八位中英文或数字
  const teamNameRegex = /^[\u4e00-\u9fa5a-zA-Z0-9]{2,8}$/;
  if (!teamNameRegex.test(teamName)) {
    showToast('队伍名必须是2~8位中英文或数字');
    return false;
  }

  // 校验队伍描述：100字符以内
  if (teamDesc.length > 100) {
    showToast('队伍描述不能超过100个字符');
    return false;
  }

  // 校验最大人数：不超过100人
  if (maxMember < 1 || maxMember > 100) {
    showToast('最多人数必须在1到100之间');
    return false;
  }

  if (teamForm.value.type === 1) {
    // 校验队伍密码：4-16位，必须包含字母和数字
    const passwordRegex = /^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d]{4,16}$/;
    if (!passwordRegex.test(teamPassword)) {
      showToast('队伍密码必须是4-16位，且包含字母和数字');
      return false;
    }
  }

  if (teamForm.value.isLimit === 1) {
    if (!teamForm.value.beginTime || !teamForm.value.endTime) {
      showToast('请选择限时时间');
      return false;
    }

    const formatDateTime = (dateTime) => {
      // Check if format already includes seconds
      if (dateTime.includes('T') && dateTime.split('T')[1].length === 8) {
        return dateTime;
      }

      // Format to 'yyyy-MM-ddTHH:mm:ss'
      const [date, time] = dateTime.split(' ');
      return `${date}T${time}:00`; // Appending seconds as ':00'
    };

    teamForm.value.beginTime = formatDateTime(teamForm.value.beginTime);
    teamForm.value.endTime = formatDateTime(teamForm.value.endTime);
  }

  if (teamForm.value.tags.length === 0) {
    showToast('请选择标签');
    return false;
  }
  // 所有验证通过
  return true;
};

/**
 * 选择标签
 */
const onClickTag = () => {
  router.replace({path: '/team/tag'})
}

/**
 * 获取历史标签
 */
const getHistoryTags = () => {
  const tagStore = useTeamTagStore()
  teamForm.value.tags = tagStore.getAllTag()
}


/**
 * 表单数据操作
 */
const getFormData = () => {
  const formStore = useTeamFormStore()
  teamForm.value = formStore.getTeamForm()
}

const setFormData = () => {
  const formStore = useTeamFormStore()
  formStore.setTeamForm(teamForm.value)
}

onMounted(() => {
  setDate()
  getFormData()
  getHistoryTags()
})

onBeforeUnmount(
  () => {
    setFormData()
  }
)
</script>

<template>
  <div class="add-team-page">
    <van-nav-bar
      fixed
      left-arrow
      left-text="返回"
      placeholder
      right-text="创建"
      title="创建队伍"
      @click-left="onClickLeft"
      @click-right="onClickRight"
    />
    <div class="form-container">
      <div class="team-form">
        <div class="form-item upload">
          <span>封面</span>
          <van-uploader></van-uploader>
        </div>
        <div class="form-item">
          <span>队名</span>
          <input v-model="teamForm.teamName" class="inp" maxlength="8" placeholder="请输入队伍名称" type="text">
        </div>
        <div class="form-item">
          <span>简介</span>
          <div class="textarea-container">
              <textarea
                v-model="teamForm.teamDesc"
                maxlength="100"
                placeholder="请输入队伍简介"
              ></textarea>
            <div class="char-count">{{ charCount }}/100</div>
          </div>
        </div>
        <div class="form-item">
          <span>人数</span>
          <van-stepper v-model="teamForm.maxMember" max="100" min="1"/>
        </div>
        <div class="form-item">
          <span>加密</span>
          <van-switch v-model="teamForm.type" :active-value="1" :inactive-value="0" size="28px" style="margin-right: 10px"/>
          <input v-if="teamForm.type" v-model="teamForm.teamPassword" class="inp" maxlength="16"
                 placeholder="请输入队伍密码" type="password">
        </div>
        <div class="form-item">
          <span>权限</span>
          <span>未经同意可直接进队</span>
          <van-switch v-model="teamForm.isJoin" :active-value="1" :inactive-value="0" size="28px" style="margin-right: 10px"/>
        </div>
        <div class="form-item">
          <span>位置</span>
          <span>可被附近的人发现</span>
          <van-switch v-model="teamForm.isFound" :active-value="1" :inactive-value="0" size="28px" style="margin-right: 10px"/>
        </div>
        <div class="form-item">
          <span>限时</span>
          <span>是否限时进入</span>
          <van-switch v-model="teamForm.isLimit" :active-value="1" :inactive-value="0" size="28px" style="margin-right: 10px"/>
        </div>
        <div v-if="teamForm.isLimit" class="form-item">
          <span>时间</span>
          <span @click="chooseTime(0)">{{ teamForm.beginTime || '开始时间' }}</span>
          <span>~</span>
          <span @click="chooseTime(1)">{{ teamForm.endTime || '结束时间' }}</span>
        </div>
        <div class="form-item">
          <span>标签</span><span v-if="teamForm.tags.length === 0" @click="onClickTag">为队伍选择一些标签</span>
          <div v-else class="tag" @click="onClickTag">
            <van-tag v-for="tag in teamForm.tags" :key="tag.id" class="tag-item" size="medium" type="primary">
              {{ tag.text }}
            </van-tag>
          </div>
          <van-icon name="arrow"/>
        </div>
        <div class="add-btn" @click="onClickRight">创建队伍</div>
      </div>
      <van-popup
        v-model:show="timeDialog"
        :style="{ height: '60%' }"
        position="bottom"
        round
      >
        <van-picker-group
          :tabs="['选择日期', '选择时间']"
          title="选择时间"
          @cancel="onCancel"
          @confirm="onConfirm"
        >
          <van-date-picker
            v-model="currentDate"
            :max-date="maxDate"
            :min-date="minDate"
          />
          <van-time-picker v-model="currentTime"/>
        </van-picker-group>
      </van-popup>
    </div>

  </div>
</template>

<style scoped>
.add-team-page {
  min-height: 100vh;
  background: #f8f8f8;
}

.form-container {
  padding: 16px;
}

.team-form {
  padding: 0 10px;
  background-color: #ffffff;
}

.form-item {
  border-bottom: 1px solid #f3f1f2;
  padding: 8px;
  margin-bottom: 7px;
  display: flex;
  align-items: center;

}

.form-item-checked {
  border-bottom: 1px solid #f3f1f2;
  padding: 8px;
  margin-bottom: 7px;
  display: flex;
  align-items: center;
  font-size: 14px;
}

.form-item .inp {
  display: block;
  border: none;
  outline: none;
  height: 32px;
  font-size: 14px;
  flex: 1;
}

.form-item span {
  margin-right: 8px;
  font-size: 14px;
  color: #4e4e4e;
}

/* 队伍简介*/
.textarea-container {
  position: relative;
}

textarea {
  width: 70vw;
  height: 60px; /* 3行高度 */
  resize: none; /* 禁用手动调整大小 */
  border: none;
  border-radius: 4px;
  box-sizing: border-box; /* 包括内边距和边框 */
  font-size: 14px;
}

.char-count {
  position: absolute;
  bottom: 10px;
  right: 10px;
  font-size: 0.9em;
  color: #666;
}

/* 创建队伍*/
.add-btn {
  width: 100%;
  height: 42px;
  margin-top: 10px;
  background: linear-gradient(90deg, #3cd7ec, #1125ff);
  color: #fff;
  font-size: 18px;
  border-radius: 39px;
  box-shadow: 0 10px 20px 0 rgba(0, 0, 0, .1);
  letter-spacing: 2px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.add-btn:active {
  background: linear-gradient(90deg, #3cd7ec, rgba(17, 37, 255, 0.76));
}

/* 标签*/
.tag {
  display: flex;
  flex-wrap: wrap;
}

.tag .tag-item {
  color: #f1f1f1;
  margin-top: 6px;
  margin-right: 6px;
}
</style>
